package com.netcracker.studies;

import Bank.Account;
import Bank.MD5Utils;
import Bank.User;
import Beans.AuthorizationBean;
import Beans.AuthorizationBeanInterface;
import DBConnection.DBAPI;
import DBConnection.DBObject;
import DBConnection.DBTools;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;


@WebServlet(name = "RegistrationServlet")
public class RegistrationServlet extends BaseServlet {
    private static final Logger log = Logger.getLogger(AuthorizationBean.class);
    protected void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain; charset=utf-8");
        try {
            DBObject obj = new DBObject(DBTools.getNewID(), DBAPI.USER, request.getParameter("login"), null, null, new HashMap<BigInteger, Object>());
            obj.setAttribute(DBAPI.ATTR_LOGIN, request.getParameter("user_login"));
            obj.setAttribute(DBAPI.ATTR_USER_NAME, request.getParameter("user_fname"));
            obj.setAttribute(DBAPI.ATTR_PASSWORD, request.getParameter("password"));
            obj.setAttribute(DBAPI.ATTR_PHONE, request.getParameter("user_tel"));
            obj.setAttribute(DBAPI.ATTR_MAIL, request.getParameter("user_email"));

            DBAPI.insertObject(obj);

            //Create new Account
            DBObject acc = new DBObject(DBTools.getNewID(), DBAPI.ACCOUNT,request.getParameter("login") + " acc", null, null, new HashMap<BigInteger, Object>());
            acc.setAttribute(DBAPI.ATTR_ACCOUNT_NUMBER, DBTools.getNewAccNumber());
            acc.setAttribute(DBAPI.ATTR_AMOUNT, 0);
            acc.setAttribute(DBAPI.ATTR_USER_ID, obj.getID());
            DBAPI.insertObject(acc);
            response.sendRedirect("index.jsp");

        } catch (Exception e) {
            throw new ServletException(e.getMessage());
        }
    }

    protected void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //response.getWriter().write("registration.jsp");
        request.getRequestDispatcher("registration.jsp").forward(request,response);
    }
}
